let MONSTER_TABLE = {
    enemy301: {
        hp: 100,
        attack: 10,
        attackcd: 0.5,
    },
    enemy302: {
        hp: 50,
        attack: 10,
        attackcd: 0.5,
    },
    enemy303: {
        hp: 75,
        attack: 10,
        attackcd: 0.5,
    },
};

class CMonsterManager {
    constructor() {
        this._allMonster = {}; //所有怪物
        this._monsterid = 1; //怪物id

        //cc.loader.loadRes(资源路径，资源类型，回调函数) 动态加载血量提示
        cc.loader.loadRes("panel/panelHurt", cc.Prefab, (err, item) => {
            if (err) {
                cc.log("资源加载错误", err);
                return;
            }
            this._hurtLabel = item;
        });
    }

    update(dt) {
        for (let id in this._allMonster) { 
            this._allMonster[id].time -= dt;
        }
        this.moveToTarget();
    }

    //添加怪物
    addMonster(monster) {
        let name = monster.name;
        let info = MONSTER_TABLE[name];
        monster.id = this._monsterid++;
        monster.hp = info.hp; //血量
        monster.attack = info.attack; //攻击力
        monster.attackcd = info.attackcd; //攻击冷却
        monster.time = 0;
        this._allMonster[monster.id] = monster;
    }

    removeMonster(monster) {
        if (monster.isDead) return; 
        monster.isDead = true;
        monster.destroy(); //销毁该节点，在本帧末尾回收到对象池
        if (this._allMonster[monster.id]) {
            delete this._allMonster[monster.id]; //delete  删除对象中某个键
        }
    }

    getMonster(id) {
        return this._allMonster[id];
    }

    //获取所有怪物
    getAllMonster() {
        return Object.values(this._allMonster); //Object.values() 获取对象中所有值
    }

    //接近目标
    moveToTarget() {
        let speed = 4;
        for (let id in this._allMonster) {
            //in是遍历对象中所有键
            let monster = this._allMonster[id];
            let role = monster.target;
            if (!role) continue;
            let dis = role.getPosition().sub(monster.getPosition()); //sub计算向量差
            if (dis.mag() <= 50) continue; //向量.mag() 获取向量长度
            let randomY = Math.random() * 2;
            if (!monster.randomY) monster.randomY = randomY; //将怪物随机值记录下来

            let hd = cc.v2(1, randomY).signAngle(dis); //计算弧度
            let hd2 = cc.v2(1, 0).signAngle(dis); //计算两向量夹角
            let angle = (hd2 * 180) / Math.PI;
            monster.x += speed * Math.cos(hd);
            monster.y += speed * Math.sin(hd);
            monster.angle = angle - 90;
        }
    }

    
    //击中怪物
    onHurt(bullet, monster) {
        //子弹击中怪物
        g_Bullet.removeBullet(bullet);
        let hurt = Math.floor((bullet.attack * Math.floor(90 + Math.random() * 21)) / 100); //90%-110% 攻击力

        g_Game.playEffect(110, monster.getPosition());
        this.receiveDamage(monster, hurt, DAMAGE_TYPE.NORMAL, bullet.owner.hitRate);//怪物受伤
        
    }

    //怪物受伤
    receiveDamage(monster, hurt, type, ...args) {
        if (monster.isDead) return; 
        
        let hurtLabel = cc.instantiate(this._hurtLabel);
        cc.find("Canvas/hurtLayer").addChild(hurtLabel);
        hurtLabel.setPosition(monster.getPosition());
        if ([...args] > Math.random()) {
            hurt = Math.floor(hurt * 1.8);
            hurtLabel.getComponent(cc.Label).string = "#" + hurt;
        } else {
            hurtLabel.getComponent(cc.Label).string = hurt;
        }
        monster.hp -= hurt;

        if (type == DAMAGE_TYPE.NORMAL) {
            //hurtLable.color = cc.color.RED; //使用系统默认的颜色：红色
            hurtLabel.color = cc.color(255, 0, 0); //使用自定义颜色：红色
        } else if(type == DAMAGE_TYPE.POISION) {
            hurtLabel.color = cc.color(0, 255, 0); //使用自定义颜色：绿色
        } else if(type == DAMAGE_TYPE.FIRE) {
            hurtLabel.color = cc.color(0, 0, 255); //使用自定义颜色：蓝色
        }
        

        hurtLabel.runAction(
            cc.sequence(
                //串行执行多个动作
                cc.scaleTo(0.1, 1.3), //缩放到指定大小 （时间，缩放值）
                cc.spawn(
                    //并行执行多个动作
                    cc.moveBy(1, 0, 100), //移动像素 （时间,x移动距离不变,y移动距离向上100）
                    cc.fadeOut(1), //淡出 （时间）
                    cc.scaleTo(1, 0) //缩放到指定大小 （时间，缩放值）
                ),

                cc.callFunc(() => {
                    //调用函数
                    hurtLabel.destroy();
                })
            )
        );

        

        if (monster.hp <= 0 && !monster.isDead) {
            this.removeMonster(monster);
            g_Slot.emit(g_Lister.monster_die, monster);
        }
    }

    doAttack(monster, role) {
        if (monster.time > 0) return;
        monster.time = monster.attackcd;
        role.getComponent("role").receiveDamage(monster.attack);//怪物攻击人物
    }

    clear() {
        this._allMonster = {};
    }

    onCollisionEnter(other, self) {
        //碰撞开始时调用
        let monster = self.node;
        if (other.node.group == "bullet") {
            this.onHurt(other.node, monster);
            other.node.owner.addBulletdebuff(monster);
        } else if (other.node.group == "role") {
            this.doAttack(monster, other.node);
        }
    }

    onCollisionStay(other, self) {
        let monster = self.node;
        if (other.node.group == "role") {
            this.doAttack(monster, other.node);
        }
        //碰撞持续时调用
    }

    onCollisionExit(other, self) {
        //碰撞离开时调用
    }
}
//window是全局变量，可以在任何地方访问到
window.g_Monster = new CMonsterManager();
